//第三方引入
import React, { lazy } from "react";
import { useRoutes, Navigate } from "react-router-dom";
import { Spin } from "antd";
import _ from "lodash";
//自定义引入
import routes from "./routers";
import type { routeType } from "./type/index.ts";
import type { resType } from "@/declare/request";

export default function Routes() {
   // 合并 myRoutes 和其他路由
   const allRoutes = [
    ...routes, // 常规路由
  ];

  const element = useRoutes(renderRoutes(allRoutes));
  return element;
}

function renderRoutes(routes: Array<routeType>): any {
  return _.map(routes, (item: routeType) => {
    let res: resType = { ...item };
    if (!item.path) return;
    //组件？
    if (item?.component) {
      const Component = lazy(item.component);
      res.element = (
        <React.Suspense fallback={<Spin size="large" />}>
          <BeforeEach route={item}>
            <Component />
          </BeforeEach>
        </React.Suspense>
      );
    }

    // children
    if (item?.children && _.isArray(item?.children)) {
      res.children = renderRoutes(item.children);
    }

    // 重定向
    if (item?.redirect) {
      res.element = <Navigate to={item.redirect} replace />;
    }
    return res;
  });
}

//前置守卫
function BeforeEach(props: { route: routeType; children: any }) {
  if (props?.route?.meta?.title) {
    document.title = props.route.meta.title;
  }

  if (props?.route?.meta?.needLogin) {
    // 看是否登录
    // const navigate = useNavigate();
    // navigate('/login');
  }

  return <div>{props.children}</div>;
}
